<template>
  <div class="card content-box">
    <el-form label-width="168px" :model="state.videoForm" ref="ruleVideoRef" :rules="videoRole">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="视频上传：" prop="filepath">
            <el-upload
              :action="state.uploadUrl"
              :list-type="state.videoForm.filepath ? '' : 'picture-card'"
              :accept="state.uploadFormat"
              :file-list="(state.videoForm.filepathArrTemp = [])"
              :on-success="handleFileSuccess"
              :before-upload="file => handleBeforeUpload(file, state.uploadFormat)"
            >
              <div class="upload-see" v-if="state.videoForm.filepath" :style="{ border: '1px solid #c0ccda' }">
                <img :src="state.thumbnailUrl" class="upload-image" />
                <div class="upload-handle" @click.stop>
                  <div class="handle-icon" @click="handleRemove('file')">
                    <el-icon>
                      <Delete />
                    </el-icon>
                    <span>删除</span>
                  </div>
                </div>
              </div>
              <div v-else class="upload-def">
                <img src="@/assets/images/video/upload-video.png" alt="" class="img-def" />
                <span>请上传视频</span>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button @click="printable">打印</el-button>
  </div>
</template>

<script setup name="authMenu">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { formatFileSize } from "@/utils/index.ts";
const state = reactive({
  uploadUrl: import.meta.env.VITE_API_URL + "/file/upload",
  uploadFormat: "video/mp4, video/ogg, video/webm",
  videoForm: {
    filepath: "",
    filepathArrTemp: [],
    filesize: 0,
    changeSIze: "",
    totalTime: 0
  },
  thumbnailUrl: ""
});
const ruleVideoRef = ref(null);
const videoRole = ref({
  filepath: [{ required: true, message: "请上传视频", trigger: "blur" }] // 视频路径
});

// 删除
const handleRemove = val => {
  console.log(val);
  if (val == "file") {
    state.videoForm.filepath = "";
    state.videoForm.filepathArrTemp = [];
    state.videoForm.filesize = 0;
    state.videoForm.changeSIze = "";
    state.videoForm.totalTime = 0;
    state.thumbnailUrl = "";
  }
};

const handleFileSuccess = res => {
  console.log(res);
  state.videoForm.filepath = res.data.url;
  // ElMessage.success("上传成功");
  ruleVideoRef.value.clearValidate("filepath");
};

const handleBeforeUpload = (file, fileType) => {
  // console.log(file);
  if (validateFormat(file, fileType)) {
    // 获取文件大小
    getVideoSize(file);
    // 获取视频封面
    getVideoFace(file);
  } else {
    // 必须返回 false，阻止自动上传
    return false;
  }
};

// 校验视频格式
const validateFormat = (file, fileType) => {
  // 参数校验
  if (!file || !fileType) {
    ElMessage.error("文件或文件类型参数缺失");
    console.error("文件或文件类型参数缺失");
    return false;
  }

  // 将允许的文件类型字符串转换为数组
  const allowedTypes = fileType.split(",").map(type => type.trim());

  // 检查文件类型是否在允许的列表中
  const isValidType = allowedTypes.some(allowedType => {
    // 处理通配符类型（如 video/*）
    if (allowedType.includes("/*")) {
      const category = allowedType.split("/*")[0];
      return file.type.startsWith(category + "/");
    }
    // 精确匹配
    return file.type === allowedType;
  });

  if (!isValidType) {
    ElMessage.error(`文件格式不支持。允许的格式：${fileType}，当前文件格式：${file.type}`);
    console.error(`文件格式不支持。允许的格式：${fileType}，当前文件格式：${file.type}`);
    return false;
  }

  console.log("文件格式校验通过");
  return true;
};

const getVideoSize = file => {
  // 获取文件大小
  // console.log(file.size);
  state.videoForm.filesize = file.size;
  // 格式化文件大小
  state.videoForm.changeSIze = formatFileSize(file.size);
  const isLt = file.size / 1024 / 1024 < 2;
  // 读取文件
  const video = document.createElement("video");
  const reader = new FileReader();

  reader.onload = async e => {
    video.src = e.target.result;
    await new Promise(resolve => {
      video.onloadedmetadata = () => {
        resolve();
      };
    });

    // 获取视频时长（单位秒）
    const durationInSeconds = Math.round(video.duration);
    // console.log("视频时长（秒）:", state.videoForm.totalTime);
    // 在这里可以将 durationInSeconds 存储或传递给其他地方
    state.videoForm.totalTime = durationInSeconds;

    video.src = "";
  };

  reader.readAsDataURL(file);
};

const getVideoFace = file => {
  // 获取视频的第一帧做封面图
  // 创建视频元素
  const video = document.createElement("video");
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");

  // 创建对象URL
  const url = URL.createObjectURL(file);

  video.src = url;

  // 当视频元数据加载完成
  video.addEventListener("loadedmetadata", () => {
    // 设置canvas尺寸与视频相同
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    // 尝试获取第一帧
    video.addEventListener("seeked", () => {
      // 在canvas上绘制视频帧
      context.drawImage(video, 0, 0, canvas.width, canvas.height);

      /// 将canvas转为DataURL并保存到data中
      state.thumbnailUrl = canvas.toDataURL("image/jpeg", 0.9);
      // console.log("视频封面:", state.thumbnailUrl);
      URL.revokeObjectURL(url);
    });

    // 设置当前时间为0.1秒（有些视频第一帧可能是黑屏，稍微往后一点）
    video.currentTime = 0.1;
  });

  video.load();
};

const printable = () => {
  console.log(state.videoForm);
  console.log(state.thumbnailUrl);
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
